using System;
using System.Data;

namespace Magiq.Databases
{
    public static class CommandExtension
    {
        public static int ExecuteNonQuerySafe(this IDbCommand self)
        {
            var haveToOpenTheConnection = self.Connection.State != ConnectionState.Open;

            if (haveToOpenTheConnection)
                self.Connection.Open();

            var result = self.ExecuteNonQuery();

            if (haveToOpenTheConnection)
                self.Connection.Close();

            return result;
        }

        public static T Run<T>(this IDbConnection self, Func<IDbConnection, T> action)
        {
            var haveToOpenTheConnection = self.State != ConnectionState.Open;

            if (haveToOpenTheConnection)
                self.Open();

            var result = action(self);

            if (haveToOpenTheConnection)
                self.Close();

            return result;
        }

        public static void Run(this IDbConnection self, Action<IDbConnection> action)
        {
            var haveToOpenTheConnection = self.State != ConnectionState.Open;

            if (haveToOpenTheConnection)
                self.Open();

            action(self);

            if (haveToOpenTheConnection)
                self.Close();
        }
    }
}